import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { ElTree } from 'element-plus';

import { userList, addUser, updateUser, delUser } from '@/utils/api/system/user'
import { ListRole } from '@/utils/api/system/role'
import { ResetPassword } from '@/utils/api/login'

export function useDept() {
  const form = reactive({
    UserName: "",
    fullName: "",
    pageNumber: 0,
    pageSize: 10,
    sortName: "createtime",
    sortType: 0
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const { tagStyle } = usePublicHooks();
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "账户名",
      prop: "username",
      width: 150,
      align: "left"
    },
    {
      label: "姓名",
      prop: "realname",
      width: 150,
      align: "left"
    },
    {
      label: "角色",
      prop: "RoleNames",
      width: 250,
      align: "left"
    },
    {
      label: "手机号",
      prop: "mobile",
      width: 150,
      align: "left"
    },
    {
      label: "用户状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "禁用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      prop: "createtime",
      minWidth: 200,
      formatter: ({ createTime }) => dayjs(createTime).format("YYYY-MM-DD HH:mm:ss"),
      sortable: true
    },
    {
      label: "操作",
      fixed: "right",
      width: 250,
      slot: "operation"
    }
  ]

  async function onSearch() {
    loading.value = true;
    const { Content } = await userList(form);
    let newData = Content.Results;
    dataList.value = newData;
    pagination.total = Content.TotalCount;
    pagination.pageSize = Content.PageSize;
    pagination.currentPage = Content.PageNumber + 1;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // 重置
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function openDialog(title = "新增", row?: FormItemProps) {
    let { Content } = await ListRole()
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          Username: row?.username ?? "",
          realname: row?.realname ?? "",
          Mobile: row?.mobile ?? null,
          Status: row?.status ?? 1,
          RoleIds: row?.RoleIds ?? [],
          Note: row?.note ?? "",
        },
        roles: Content ?? []
      },
      width: "35%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(elForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了用户名称为${curData.Username}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              addUser(curData).then(res => {
                if (res.Code === 0) chores();
              })
            } else {
              let data = Object.assign(curData, { Id: row.id })
              updateUser(data).then(res => {
                if (res.Code === 0) chores();
              })
            }
          }
        });
      }
    })
  }

  // 重置密码
  function resetPass(row){
    ElMessageBox.confirm(
      `是否确认重置密码？`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',                      
        center: true,
      }
    ).then(() => {
      ResetPassword({userId:row.id}).then(res => {
        if (res.Code === 0) {
          message(`重置成功`, { type: "success" });
          onSearch();
        }
      })
    }).catch(() => { })
  }

  // 删除
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否确认删除用户为${row.realname}的数据项?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      }
    ).then(() => {
      delUser(row.id).then(res => {
        if (res.Code === 0) {
          message(`您删除了用户为${row.realname}的这条数据`, { type: "success" });
          onSearch();
        }
      })
    }).catch(() => { })
  }

  function handleSizeChange(val: number) {
    form.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    form.pageNumber = val - 1
    onSearch()
  }

  onMounted(() => {
    onSearch()
  })

  return {
    columns,
    loading,
    dataList,
    openDialog,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    resetPass
  }
}